package com.xuegao.xuegaotool;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * <br/> @PackageName：com.xuegao.xuegaotool
 * <br/> @ClassName：JpegChangeDpi
 * <br/> @Description：
 * <br/> @author：xuegao
 * <br/> @date：2020/12/24 18:49
 */
public class JpegChangeDpi {

    public static void handleDpi(File file, File newFile, int xDensity, int yDensity) {
        try {
            // image1(file, newFile, xDensity, yDensity);
            imageCopy(file, newFile, xDensity, yDensity);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void image1(File file, File newFile, int xDensity, int yDensity) throws IOException {
        BufferedImage image = ImageIO.read(file);
        JPEGImageEncoder jpegEncoder = JPEGCodec.createJPEGEncoder(new FileOutputStream(newFile));
        JPEGEncodeParam jpegEncodeParam = jpegEncoder.getDefaultJPEGEncodeParam(image);
        jpegEncodeParam.setDensityUnit(JPEGEncodeParam.DENSITY_UNIT_DOTS_INCH);
        jpegEncoder.setJPEGEncodeParam(jpegEncodeParam);
        jpegEncodeParam.setQuality(0.75f, false);
        jpegEncodeParam.setXDensity(xDensity);
        jpegEncodeParam.setYDensity(yDensity);
        jpegEncoder.encode(image, jpegEncodeParam);
        image.flush();
    }

    private static void imageCopy(File file, File newFile, int xDensity, int yDensity) throws IOException {
        BufferedImage inImg = ImageIO.read(file);

        // https://www.oschina.net/question/153568_37913
        int height = inImg.getHeight();
        int width = inImg.getWidth();
        BufferedImage outImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        AffineTransform affineTransform = new AffineTransform();
        affineTransform.setToScale(1, 1);
        Graphics2D gd2 = outImg.createGraphics();
        gd2.drawImage(inImg, affineTransform,null);
        gd2.dispose();
        // ImageIO.write(outImg, "jpg", newFile);

        JPEGImageEncoder jpegEncoder = JPEGCodec.createJPEGEncoder(new FileOutputStream(newFile));
        JPEGEncodeParam jpegEncodeParam = jpegEncoder.getDefaultJPEGEncodeParam(outImg);
        jpegEncodeParam.setDensityUnit(JPEGEncodeParam.DENSITY_UNIT_DOTS_INCH);
        jpegEncoder.setJPEGEncodeParam(jpegEncodeParam);
        jpegEncodeParam.setQuality(0.75f, false);
        jpegEncodeParam.setXDensity(xDensity);
        jpegEncodeParam.setYDensity(yDensity);
        jpegEncoder.encode(outImg, jpegEncodeParam);
        outImg.flush();
    }
}